/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import Interaction.ServerConnection;
import java.rmi.RemoteException;

import Flightadministration.*;
import Data.*;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */
public class AircraftManage extends JPanel {

    final Main td;
    private JPanel jp;
    public DefaultTableModel model;
    public JTable table;
    public Vector<Vector> rowData;
    public Vector<String> columnNames;
    public int currentAircraftId;
    final AircraftEdit ace;
    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
     *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public AircraftManage(final Main td, final AircraftEdit ace) throws RemoteException {

        this.td = td;
        this.ace = ace;
        showAircraftManage();
    }

    // Methoden
    public void showAircraftManage() throws RemoteException {

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************

        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren

        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Übersicht aller Flugzeuge</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 3;
        jp.add(headline, constraints);

        //JTable
        //**********************************************************************

        // Vector für Spaltenüberschrift mit Werten belegen
        columnNames = new Vector<String>();
        columnNames.add("ID");
        columnNames.add("Kennzeichen");
        columnNames.add("Flugzeugtyp");
        columnNames.add("Fluglinie");

        // Vector mit allen Airports aus DB
        rowData = admin.getAllAircraftsForTable();

        model = new DefaultTableModel( rowData, columnNames );
        model.addTableModelListener(table);
        table = new JTable(model) {
            @Override
            public boolean isCellEditable(int x, int y) {
                return false;
            }
        };
        table.setModel(model);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(10);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        table.setPreferredScrollableViewportSize(new Dimension(550,450));
        table.setVisible(true);
        jp.add( new JScrollPane(table), constraints);


        //Buttons
        //**********************************************************************

        JButton button_CreateAircraft = new JButton("Anlegen");
        constraints.gridwidth = 1;
        constraints.gridx = 0;
        constraints.gridy = 2;
        jp.add(button_CreateAircraft, constraints);

        JButton button_EditAircraft = new JButton("Editieren");
        constraints.gridx = 1;
        constraints.gridy = 2;
        jp.add(button_EditAircraft, constraints);

        JButton button_DeleteAircraft = new JButton("Löschen");
        constraints.gridx = 2;
        constraints.gridy = 2;
        jp.add(button_DeleteAircraft, constraints);


        //ActionListener
        //**********************************************************************
        table.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){

                //Nur auf Doppelklick der linken Mousetaste reagieren.
                if(evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1){
                    edit();
                }
            }
        });

        button_CreateAircraft.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){

                ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AircraftC");
            }
        });


        button_EditAircraft.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                } else {
                    edit();
                }
            }
        });


        button_DeleteAircraft.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {

                    int iSelectedRow = table.getSelectedRow();

                    Object[] options = {"Ja", "Nein"};

                    String txt = "<html><p style=\"color:red; text-align: center\">Flugzeug <i><u>"
                                    + table.getModel().getValueAt(iSelectedRow, 1)
                                    + "</i></u> wirklich löschen? Dabei werden auch alle damit <br>"
                                    + "in Verbindung stehenden Flugdurchführungen und Buchungen gelöscht</p></html>";
                    int n = JOptionPane.showOptionDialog(td, txt, "Flugzeug löschen",
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        options,
                        options[1]);

                        if (n == 0) {
                            try {
                                // Id des ausgewählten Flugzeuges auslesen
                                Object currentCraftId = table.getModel().getValueAt(iSelectedRow, 0);
                                    int currentCraftIdAsInt = Integer.parseInt(currentCraftId.toString());
                                // Name des ausgewählten Flugzeuges auslesen
                                Object currentCraftName = table.getModel().getValueAt(iSelectedRow, 1);
                                    String currentCraftNameAsString = String.valueOf(currentCraftName);
                                // Id der Fluglinie des ausgewählten Flugzeuges auslesen
                                Object currentAirlineName = table.getModel().getValueAt(iSelectedRow, 2);
                                    String currentAirlineNameAsString = String.valueOf(currentAirlineName);
                                        int currentAirlineId = 0;
                                            Vector<Airline> allAirlines = admin.getAllAirlinesForComboBox();
                                                for(int i=0; i<allAirlines.size(); i++) {
                                                    if(allAirlines.get(i).getAirName().equals(currentAirlineNameAsString)) {
                                                        currentAirlineId = allAirlines.get(i).getAirId();
                                                    }
                                                }
                                // Id des Flugzeugtyps des ausgewählten Flugzeuges auslesen
                                Object currentTypeOfAircraftName = table.getModel().getValueAt(iSelectedRow, 3);
                                    String currentTypeOfAircraftNameAsString = String.valueOf(currentTypeOfAircraftName);
                                        int currentTypeOfAircraftId = 0;
                                            Vector<TypeOfAircraft> allTypeOfAircrafts = admin.getAllTypeOfAircraftsForComboBox();
                                                for(int i=0; i<allTypeOfAircrafts.size(); i++) {
                                                    if(allTypeOfAircrafts.get(i).getCraftTypeName().equals(currentTypeOfAircraftNameAsString)) {
                                                        currentTypeOfAircraftId = allTypeOfAircrafts.get(i).getCraftTypeId();
                                                    }
                                                }

                                // Flugzeugobjekt aus der Datenbank löschen
                                admin.deleteAircraft(currentCraftIdAsInt, currentCraftNameAsString, currentAirlineId, currentTypeOfAircraftId);
                                    // JTables aktualisieren
                                    td.updateAircraft();
                                    td.updateFlightRealization();
                                    
                                JOptionPane.showMessageDialog(null, "Flugzeug gelöscht");

                            } catch (RemoteException ex) {
                                Logger.getLogger(AirportManage.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                }
            }
        });

    }

    public void edit() {
                    int iSelectedRow = table.getSelectedRow();
                    Object currentAircraftIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
                       String currentAircraftIdAsString = String.valueOf(currentAircraftIdasObject);
                            currentAircraftId = Integer.parseInt(currentAircraftIdAsString);
                        try {
                            Aircraft a = admin.getAircraftById(currentAircraftId);

                            ace.label2.setText(String.valueOf(a.getCraftId()));

                            ace.textfield1.setText(a.getCraftName());
                            ace.currentAircraftName = a.getCraftName();
                            
                            // Flugzeugtyp auslesen und übergeben
                            ace.label6.setText(String.valueOf(table.getModel().getValueAt(iSelectedRow, 2)));

                            // Fluglinie auslesen und übergeben
                            Object currentAirline = table.getModel().getValueAt(iSelectedRow, 3);
                            ace.comboBox2.setSelectedItem(currentAirline);

                            ((CardLayout) td.rightp.getLayout()).show(td.rightp, "AircraftE");

                        } catch (RemoteException ex) {
                            System.out.println(ex);
                        }
    }

    public void updateTableData() throws RemoteException {

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllAircraftsForTable();

        // Tabelleninhalt wird aktualisiert
        model.setDataVector(rowData, columnNames);

    }
    
    public JPanel getJp() {
        return jp;
    }
}

